#!/bin/bash

# =============================================================================
# 百联仓库物流管理系统 - 正式环境启动脚本
# 版本: 3.9.0
# 作者: 系统管理员
# 描述: 自动检查并启动所有必要的服务，然后启动百联系统
# =============================================================================

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否为root用户
check_root() {
    if [[ $EUID -eq 0 ]]; then
        log_warning "检测到root用户，建议使用普通用户运行此脚本"
        read -p "是否继续? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            exit 1
        fi
    fi
}

# 检查操作系统
check_os() {
    log_info "检测操作系统..."
    if [[ "$OSTYPE" == "linux-gnu"* ]]; then
        OS="linux"
        log_success "检测到Linux系统"
    elif [[ "$OSTYPE" == "darwin"* ]]; then
        OS="macos"
        log_success "检测到macOS系统"
    else
        log_error "不支持的操作系统: $OSTYPE"
        exit 1
    fi
}

# 检查Java环境
check_java() {
    log_info "检查Java环境..."
    
    if command -v java &> /dev/null; then
        JAVA_VERSION=$(java -version 2>&1 | head -n 1 | cut -d'"' -f2)
        log_success "检测到Java版本: $JAVA_VERSION"
        
        # 检查Java版本是否符合要求 (需要Java 8+)
        JAVA_MAJOR=$(echo $JAVA_VERSION | cut -d'.' -f1)
        if [[ "$JAVA_MAJOR" == "1" ]]; then
            JAVA_MAJOR=$(echo $JAVA_VERSION | cut -d'.' -f2)
        fi
        
        if [[ $JAVA_MAJOR -lt 8 ]]; then
            log_error "Java版本过低，需要Java 8或更高版本"
            exit 1
        fi
        
        # 检查JAVA_HOME
        if [[ -z "$JAVA_HOME" ]]; then
            log_warning "JAVA_HOME环境变量未设置"
            # 尝试自动设置JAVA_HOME
            if [[ "$OS" == "linux" ]]; then
                JAVA_HOME=$(dirname $(dirname $(readlink -f $(which java))))
            elif [[ "$OS" == "macos" ]]; then
                JAVA_HOME=$(/usr/libexec/java_home)
            fi
            export JAVA_HOME
            log_info "自动设置JAVA_HOME: $JAVA_HOME"
        else
            log_success "JAVA_HOME: $JAVA_HOME"
        fi
    else
        log_error "未检测到Java环境，请先安装Java 8或更高版本"
        exit 1
    fi
}

# 检查Maven环境
check_maven() {
    log_info "检查Maven环境..."
    
    if command -v mvn &> /dev/null; then
        MAVEN_VERSION=$(mvn -version | head -n 1 | cut -d' ' -f3)
        log_success "检测到Maven版本: $MAVEN_VERSION"
    else
        log_error "未检测到Maven环境，请先安装Maven"
        exit 1
    fi
}

# 启动MySQL服务
start_mysql() {
    log_info "检查MySQL服务状态..."
    
    if command -v mysql &> /dev/null; then
        if pgrep -x "mysqld" > /dev/null; then
            log_success "MySQL服务已在运行"
        else
            log_warning "MySQL服务未运行，尝试启动..."
            
            if [[ "$OS" == "linux" ]]; then
                if command -v systemctl &> /dev/null; then
                    sudo systemctl start mysql
                    sudo systemctl enable mysql
                elif command -v service &> /dev/null; then
                    sudo service mysql start
                else
                    log_error "无法启动MySQL服务，请手动启动"
                    return 1
                fi
            elif [[ "$OS" == "macos" ]]; then
                if command -v brew &> /dev/null; then
                    brew services start mysql
                else
                    log_error "无法启动MySQL服务，请手动启动"
                    return 1
                fi
            fi
            
            # 等待MySQL启动
            sleep 5
            if pgrep -x "mysqld" > /dev/null; then
                log_success "MySQL服务启动成功"
            else
                log_error "MySQL服务启动失败"
                return 1
            fi
        fi
    else
        log_error "未检测到MySQL，请先安装MySQL"
        return 1
    fi
}

# 启动Redis服务
start_redis() {
    log_info "检查Redis服务状态..."
    
    if command -v redis-server &> /dev/null; then
        if pgrep -x "redis-server" > /dev/null; then
            log_success "Redis服务已在运行"
        else
            log_warning "Redis服务未运行，尝试启动..."
            
            if [[ "$OS" == "linux" ]]; then
                if command -v systemctl &> /dev/null; then
                    sudo systemctl start redis
                    sudo systemctl enable redis
                elif command -v service &> /dev/null; then
                    sudo service redis start
                else
                    # 直接启动redis-server
                    nohup redis-server > /dev/null 2>&1 &
                fi
            elif [[ "$OS" == "macos" ]]; then
                if command -v brew &> /dev/null; then
                    brew services start redis
                else
                    # 直接启动redis-server
                    nohup redis-server > /dev/null 2>&1 &
                fi
            fi
            
            # 等待Redis启动
            sleep 3
            if pgrep -x "redis-server" > /dev/null; then
                log_success "Redis服务启动成功"
            else
                log_error "Redis服务启动失败"
                return 1
            fi
        fi
    else
        log_error "未检测到Redis，请先安装Redis"
        return 1
    fi
}

# 启动Nginx服务
start_nginx() {
    log_info "检查Nginx服务状态..."
    
    if command -v nginx &> /dev/null; then
        if pgrep -x "nginx" > /dev/null; then
            log_success "Nginx服务已在运行"
        else
            log_warning "Nginx服务未运行，尝试启动..."
            
            if [[ "$OS" == "linux" ]]; then
                if command -v systemctl &> /dev/null; then
                    sudo systemctl start nginx
                    sudo systemctl enable nginx
                elif command -v service &> /dev/null; then
                    sudo service nginx start
                else
                    sudo nginx
                fi
            elif [[ "$OS" == "macos" ]]; then
                if command -v brew &> /dev/null; then
                    brew services start nginx
                else
                    sudo nginx
                fi
            fi
            
            # 等待Nginx启动
            sleep 3
            if pgrep -x "nginx" > /dev/null; then
                log_success "Nginx服务启动成功"
            else
                log_error "Nginx服务启动失败"
                return 1
            fi
        fi
    else
        log_warning "未检测到Nginx，跳过Nginx启动（可选服务）"
        return 0
    fi
}

# 检查端口占用
check_ports() {
    log_info "检查端口占用情况..."
    
    local ports=("8080" "6379" "3306" "80")
    local port_names=("百联系统" "Redis" "MySQL" "Nginx")
    
    for i in "${!ports[@]}"; do
        local port=${ports[$i]}
        local name=${port_names[$i]}
        
        if lsof -i :$port > /dev/null 2>&1; then
            local process=$(lsof -i :$port | grep LISTEN | head -1 | awk '{print $1}')
            log_success "$name 端口 $port 已被 $process 占用"
        else
            log_warning "$name 端口 $port 未被占用"
        fi
    done
}

# 创建必要的目录
create_directories() {
    log_info "创建必要的目录..."
    
    local dirs=(
        "logs"
        "uploadPath"
        "temp"
        "backup"
    )
    
    for dir in "${dirs[@]}"; do
        if [[ ! -d "$dir" ]]; then
            mkdir -p "$dir"
            log_success "创建目录: $dir"
        else
            log_info "目录已存在: $dir"
        fi
    done
}

# 编译项目
build_project() {
    log_info "开始编译项目..."
    
    # 清理之前的编译文件
    log_info "清理之前的编译文件..."
    mvn clean -q
    
    # 编译项目
    log_info "编译项目..."
    if mvn compile -q; then
        log_success "项目编译成功"
    else
        log_error "项目编译失败"
        exit 1
    fi
    
    # 打包项目
    log_info "打包项目..."
    if mvn package -DskipTests -q; then
        log_success "项目打包成功"
    else
        log_error "项目打包失败"
        exit 1
    fi
}

# 启动百联系统
start_bailian() {
    log_info "启动百联系统..."
    
    # 检查JAR文件是否存在
    local jar_file="bailian-admin/target/bailian-admin.jar"
    if [[ ! -f "$jar_file" ]]; then
        log_error "未找到JAR文件: $jar_file"
        log_info "请先运行编译步骤"
        exit 1
    fi
    
    # 设置生产环境配置
    export SPRING_PROFILES_ACTIVE=prod
    
    # 启动应用
    log_info "使用生产环境配置启动应用..."
    nohup java -Xms512m -Xmx1024m -XX:MetaspaceSize=128m -XX:MaxMetaspaceSize=256m \
        -Dspring.profiles.active=prod \
        -Dfile.encoding=UTF-8 \
        -Duser.timezone=Asia/Shanghai \
        -jar "$jar_file" > logs/bailian.log 2>&1 &
    
    local pid=$!
    log_success "百联系统启动中，进程ID: $pid"
    
    # 等待应用启动
    log_info "等待应用启动..."
    local count=0
    while [[ $count -lt 30 ]]; do
        if curl -s http://localhost:8080/actuator/health > /dev/null 2>&1; then
            log_success "百联系统启动成功！"
            log_info "访问地址: http://localhost:8080"
            log_info "日志文件: logs/bailian.log"
            return 0
        fi
        sleep 2
        count=$((count + 1))
        echo -n "."
    done
    
    log_error "百联系统启动超时，请检查日志文件: logs/bailian.log"
    return 1
}

# 显示系统状态
show_status() {
    log_info "系统状态检查..."
    echo "=================================="
    
    # 检查服务状态
    local services=("mysqld" "redis-server" "nginx" "java")
    local service_names=("MySQL" "Redis" "Nginx" "Java")
    
    for i in "${!services[@]}"; do
        local service=${services[$i]}
        local name=${service_names[$i]}
        
        if pgrep -x "$service" > /dev/null; then
            local pid=$(pgrep -x "$service")
            log_success "$name 运行中 (PID: $pid)"
        else
            log_warning "$name 未运行"
        fi
    done
    
    # 检查端口状态
    echo "=================================="
    check_ports
    
    # 显示系统信息
    echo "=================================="
    log_info "系统信息:"
    echo "操作系统: $OS"
    echo "Java版本: $(java -version 2>&1 | head -n 1 | cut -d'"' -f2)"
    echo "Maven版本: $(mvn -version | head -n 1 | cut -d' ' -f3)"
    echo "当前目录: $(pwd)"
    echo "=================================="
}

# 主函数
main() {
    echo "=================================="
    echo "百联仓库物流管理系统 - 正式环境启动脚本"
    echo "版本: 3.9.0"
    echo "=================================="
    
    # 检查环境
    check_root
    check_os
    check_java
    check_maven
    
    # 启动服务
    start_mysql
    start_redis
    start_nginx
    
    # 检查端口
    check_ports
    
    # 创建目录
    create_directories
    
    # 编译项目
    build_project
    
    # 启动系统
    start_bailian
    
    # 显示状态
    show_status
    
    echo "=================================="
    log_success "启动脚本执行完成！"
    echo "=================================="
}

# 错误处理
trap 'log_error "脚本执行出错，退出码: $?"' ERR

# 执行主函数
main "$@" 